/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.pwittchen.reactivenetwork.library.rx2.sample.slice;

import com.google.gson.Gson;

import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.openharmony.schedulers.OpenHarmonySchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers;

import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork;
import com.github.pwittchen.reactivenetwork.library.rx2.sample.ResourceTable;
import com.github.pwittchen.reactivenetwork.library.rx2.sample.utils.Util;
import com.github.pwittchen.reactivenetwork.library.rx2.sample.utils.ResUtil;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;

import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.LayoutScatter;

/**
 * MainAbilitySlice
 */
public class MainAbilitySlice extends AbilitySlice {
    private Text tvConnectivityStatus;

    private Text tvInternetStatus;

    private Disposable networkDisposable;

    private Disposable internetDisposable;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        Component containerComponent = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_ability_main, null, false);
        if (containerComponent instanceof ComponentContainer) {
            ComponentContainer rootLayout = (ComponentContainer) containerComponent;
            tvConnectivityStatus = ResUtil.findViewById(rootLayout, ResourceTable.Id_connectivity_status);
            tvInternetStatus = ResUtil.findViewById(rootLayout, ResourceTable.Id_internet_status);
            super.setUIContent(rootLayout);
        }
    }

    @Override
    public void onActive() {
        super.onActive();

        networkDisposable =
                ReactiveNetwork.observeNetworkConnectivity(getApplicationContext())
                        .subscribeOn(Schedulers.io())
                        .observeOn(OpenHarmonySchedulers.mainThread())
                        .subscribe(
                                connectivity -> {
                                    final boolean isAvailable = connectivity.available();
                                    final String networkCapabilities =
                                            Util.formatJsonFromString(
                                                    new Gson()
                                                            .toJson(
                                                                    connectivity
                                                                            .getNetworkState()
                                                                            .getNetworkCapabilities()));
                                    tvConnectivityStatus.setText(
                                            String.format(
                                                    "State: %s, NetworkCapabilities: %s",
                                                    isAvailable, networkCapabilities));
                                });

        internetDisposable =
                ReactiveNetwork.observeInternetConnectivity()
                        .subscribeOn(Schedulers.io())
                        .observeOn(OpenHarmonySchedulers.mainThread())
                        .subscribe(isConnected -> tvInternetStatus.setText(isConnected.toString()));
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        safelyDispose(networkDisposable, internetDisposable);
    }

    private void safelyDispose(Disposable... disposables) {
        for (Disposable subscription : disposables) {
            if (subscription != null && !subscription.isDisposed()) {
                subscription.dispose();
            }
        }
    }
}
